﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Security.Cryptography;
using System.Collections.Generic;

namespace Theosoft.Mobile.LibService
{
    public static class AESEncrypt
    {
        private static readonly byte ZeroByte = (byte)('\0');

        private static byte[] PaddingData(byte[] data)
        {
            if (data == null || data.Length == 0) return data;
            List<byte> result = new List<byte>(data);
            int padding = 16 - data.Length % 16;
            for (int i = 0; i < padding; i++)
            {
                result.Add(ZeroByte);
            }
            return result.ToArray();
        }

        public static byte[] Encrypt(byte[] buffer, byte[] key, byte[] iv)
        {
            if (buffer == null || buffer.Length == 0)
            {
                throw new ArgumentNullException("buffer");
            }

            if (key == null || key.Length == 0)
            {
                throw new ArgumentNullException("key");
            }

            if (iv == null || iv.Length == 0)
            {
                throw new ArgumentNullException("iv");
            }

            byte[] paddingBuffer = PaddingData(buffer);

            using (AesManaged aesAlg = new AesManaged())
            {
                aesAlg.KeySize = 128;
                aesAlg.BlockSize = 128;
                aesAlg.Key = key;
                aesAlg.IV = iv;
                using (ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV))
                {
                    return encryptor.TransformFinalBlock(paddingBuffer, 0, paddingBuffer.Length);
                }
            }
        }

        public static byte[] Decrypt(byte[] buffer, byte[] key, byte[] iv)
        {
            if (buffer == null || buffer.Length == 0)
            {
                throw new ArgumentNullException("buffer");
            }

            if (key == null || key.Length == 0)
            {
                throw new ArgumentNullException("key");
            }

            if (iv == null || iv.Length == 0)
            {
                throw new ArgumentNullException("iv");
            }

            using (Aes aesAlg = new AesManaged())
            {
                aesAlg.KeySize = 128;
                aesAlg.BlockSize = 128;

                aesAlg.Key = key;
                aesAlg.IV = iv;
                using (ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV))
                {
                    return decryptor.TransformFinalBlock(buffer, 0, buffer.Length);
                }
            }
        }
    }
}
